package com.xx.doublexchat.common.common.interceptor;

import cn.hutool.extra.servlet.ServletUtil;
import com.xx.doublexchat.common.common.domain.dto.RequestInfo;
import com.xx.doublexchat.common.common.utils.RequestHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 收集信息用拦截器
 */
@Component
public class CollectorInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        // 收集UID
        Long uid = Optional.ofNullable(request.getAttribute(TokenInterceptor.UID))
                .map(Object::toString)// objects -> toString
                .map(Long::parseLong).orElse(null); // Long -> parseLong方法

        // 收集IP
        String ip = ServletUtil.getClientIP(request);

        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setUid(uid);
        requestInfo.setIp(ip);
        RequestHolder.set(requestInfo);
        return true;
    }

    /**
     * 每次请求结束后移除THREAD_LOCAL
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }
}
